using System;
using System.Diagnostics.Contracts;
using OpenWaves.ActivityFeed.Web.Handler;

namespace OpenWaves.ActivityFeed.Web.Modules
{
    public class SubscriptionsModule : RestModule
    {
        public SubscriptionsModule(IActivityFeedService activityFeedService, IUserIdentityProvider identityProvider)
        {
            Contract.Requires<ArgumentNullException>(activityFeedService != null);

            this.Post("/activityFeed/subscriptions",  (request, p) =>
                                            {
                                                var dto = request.DeserializeBody<SubscriptionDto>();
                                                Contract.Assert(String.IsNullOrEmpty(dto.Topic) == false);

                                                activityFeedService.Subscribe(
                                                    identityProvider.Identity.Name, 
                                                    new[] { new Topic(dto.Topic) });

                                                return new JsonResult(Result.Ok());
                                            });

            this.Delete("/activityFeed/subscriptions/{topic}", (request, p) =>
                                            {
                                                string topic = p["topic"];
                                                Contract.Assert(String.IsNullOrEmpty(topic) == false);

                                                activityFeedService.Unsubscribe(
                                                    identityProvider.Identity.Name, 
                                                    new[] { new Topic(Url.Decode(topic)) });

                                                return new JsonResult(Result.Ok());
                                            });
        }
    }
}